<!-- RecursiveMenu.vue -->
<template>
  <el-menu
    v-if="menus.length > 0"
    :class="menuClass"
    :default-active="activePath"
    @select="handleSelect"
  >
    <template v-for="(item, index) in menus">
      <el-sub-menu
        v-if="item.children && item.children.length > 0"
        :index="item.index"
      >
        <template #title>
          <span>{{ item.name }}</span>
        </template>
        <recursive-menu
          :menus="item.children"
          :menu-class="menuClass"
          :active-path="activePath"
          :on-select="handleSelect"
        />
      </el-sub-menu>
      <el-menu-item
        v-else
        :index="item.index"
      >
        <span>{{ item.name }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup>
import { defineProps, ref, watch } from 'vue';
defineOptions({
    name: 'RecursiveMenu',
})
const props = defineProps({
  menus: {
    type: Array,
    required: true
  },
  menuClass: {
    type: String,
    default: ''
  },
  defaultActive: {
    type: String,
    default: ''
  },
  onSelect: {
    type: Function,
    default: null
  }
});
const activePath = ref(props.defaultActive);

const handleSelect = (item) => {
  activePath.value = item.index; // 更新当前激活的路径
  if (props.onSelect) {
    props.onSelect(item); // 调用父组件传递的事件处理函数
  }
};

// 监听父组件传递的 defaultActive 属性，同步更新 activePath
watch(() => props.defaultActive, (newValue) => {
  activePath.value = newValue;
});
</script>

<style>
.children {
  padding-left: 2em;
}
</style>